package com.emergency.assist.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emergency.assist.dao.RouteDao;
import com.emergency.assist.dao.RouteOptimalDao;
import com.emergency.assist.dao.RoutePointDao;
import com.emergency.assist.dao.RouteRelationDao;
import com.emergency.assist.domain.Route;
import com.emergency.assist.domain.RouteOptimal;
import com.emergency.assist.domain.RoutePoint;
import com.emergency.assist.domain.RouteRelation;
import com.emergency.assist.service.RouteService;
import com.emergency.base.domain.Scenar;
import com.emergency.common.util.CommonUtils;
import com.emergency.common.util.HttpClientUtils;
import com.emergency.common.util.IdWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by lijie on 2019/10/21.
 */

@Service
public class RouteServiceImpl implements RouteService {

    @Autowired
    private RouteDao routeDao;

    @Autowired
    private RouteRelationDao routeRelationDao;

    @Autowired
    private RoutePointDao routePointDao;

    @Autowired
    private RouteOptimalDao routeOptimalDao;

    @Autowired
    private IdWorker idWorker;

    private final static Logger logger= LoggerFactory.getLogger(RouteServiceImpl.class);
    /**
     * 初始化
    /*改变方法routePlanning(data)，参数变为（pointNumber,relationNumber,date）
    * pointNumber是表格bus_route_point的行数
    * relationNumber是表格bus_route_relation的行数
    * date是表格bus_route_relation的三个字段，分别为startPoint，endPoint，weight*/
    @Override
    public RouteOptimal routePlanning(long scenarID, String origin, String destination) {
       if(CommonUtils.isNullOrEmpty(scenarID)){//如果浏览器输入的是空值
           logger.info("输入信息为空！");
           return null;
        }
        //根据起始点查询出有几条路线
        List<Route> routes=routeDao.findAllByOriginAndDestination(origin,destination);
        if(CommonUtils.isNullOrEmpty(routes)){//如果浏览器输入的是空值
            logger.info("当前线路不存在！");
            return null;
        }
        routes.forEach(route->{
            Double weight=routeRelationDao.SumWeightByScenarAndRoute(scenarID,route.getId());
            route.setWeight(weight);
        });

        Collections.sort(routes,new Comparator<Route>() {
            public int compare(Route route1,Route route2) {
                  //对象按照权重叠加值排序
                return (int) (route1.getWeight()-route2.getWeight());
            }
        });

        //保存最终结果
       RouteOptimal routeOptimal=saveRouteOptimals(routes.get(0),scenarID);

       List<RoutePoint> routePoints=routePointDao.findAllByRoute(routeOptimal.getRoute().getId());

       routeOptimal.getRoute().setRoutePoints(routePoints);

       return routeOptimal;
    }

    private RouteOptimal saveRouteOptimals(Route route, long scenarID) {
        RouteOptimal routeOptimal=new RouteOptimal();
        routeOptimal.setId(idWorker.nextId());
        routeOptimal.setCreateTime(new Date());
        routeOptimal.setRoute(route);
        routeOptimal.setScenar(new Scenar(scenarID));
        routeOptimal.setDescrption("当前路线为最短距离");
        routeOptimalDao.saveAndFlush(routeOptimal);

        return routeOptimal;
    }


    @Override
    public void importData(String origin,String destination,int tactics) {
       // String origin="40.01116,116.339303";
        //String destination="39.936404,116.452562";
        //int tactics=0;
        JSONObject obj = HttpClientUtils.httpGet("http://api.map.baidu.com/direction/v2/driving?origin="+origin +"&destination="+ destination +"&tactics="+ tactics +"&ak=ylbSwtaIaGIEEI3stu6EqicnmzNFu5ri");
        JSONObject result= (JSONObject) obj.get("result");
        if(result!=null){
            JSONArray routeArray=result.getJSONArray("routes");
            if(routeArray.size()>0){
                routeArray.forEach(routeArr->{
                    JSONObject obj1= (JSONObject) routeArr;
                    System.out.print(routeArr);
                    Route route=new Route(idWorker.nextId());
                    route.setCreateTime(new Date());
                    route.setIsOpen(0);
                    route.setOrigin(origin);
                    route.setDestination(destination);
                    route.setDistance(obj1.getDoubleValue("distance"));
                    route.setDuration(obj1.getLong("duration"));
                    route.setTag(obj1.getString("tag"));
                    route.setTactics(tactics);
                    route.setToll(obj1.getInteger("toll"));
                    routeDao.saveAndFlush(route);

                    //保存路线节点信息
                    List<RoutePoint> pointList=new ArrayList<>();

                    JSONArray stepArray=obj1.getJSONArray("steps");
                    int sort=1;
                    if(stepArray.size()>0){
                        stepArray.forEach(step->{
                            JSONObject step1= (JSONObject) step;
                            RoutePoint point=new RoutePoint();
                            point.setId(idWorker.nextId());
                            point.setCreateTime(new Date());
                            point.setDistance(step1.getDouble("distance"));
                            point.setName(step1.getString("road_name"));
                            String startPoint=step1.getJSONObject("start_location").getString("lng")+","+
                                    step1.getJSONObject("start_location").getString("lat");
                            String endPoint=step1.getJSONObject("end_location").getString("lng")+","+
                                    step1.getJSONObject("end_location").getString("lat");
                            point.setStartLocation(startPoint);
                            point.setEndLocation(endPoint);
                            point.setRoute(route);
                            point.setPath(step1.getString("path"));
                            routePointDao.saveAndFlush(point);
                            //顺便插入关系表中
                            RouteRelation routeRelation=new RouteRelation();
                            routeRelation.setId(idWorker.nextId());
                            routeRelation.setRoute(route);
                            routeRelation.setRoutePoint(point);
                            routeRelation.setScenar(new Scenar(1l));
                            routeRelation.setWeight(point.getDistance());
                            routeRelationDao.saveAndFlush(routeRelation);
                        });

                    }

                });
            }
        }

    }
}
